#include <vector>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include "BlackQueue.hpp"

const size_t cSize=3;
const size_t pSize=3;


void* product(void* args)
{
    //cout<<"product begin"<<endl;
    BlackQueue<Task>* bq=(BlackQueue<Task>*)args;

    while(true)
    {
        int x=rand()%100+1;
        int y=rand()%100+1;
        Task task(x,y);
        //Task task(x,y,[](int a,int b){return a-b;});
        bq->push(task);
        cout<<"product:"<<x<<"+"<<y<<"=?"<<endl;
        //cout<<"product:"<<x<<"-"<<y<<"=?"<<endl;
        //usleep(1000000);
    }

    return nullptr;
}

void* consume(void* args)
{
    //cout<<"consume begin"<<endl;
    BlackQueue<Task>* bq=(BlackQueue<Task>*)args;
    while(true)
    {
        Task task;
        bq->pop(&task);
        cout<<"consume:"<<task.x_<<"+"<<task.y_<<"="<<task()<<endl;
        //cout<<"consume:"<<task.x_<<"-"<<task.y_<<"="<<task()<<endl;
        //usleep(1000000);
        sleep(3);
    }
    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr));

    // pthread_t c;
    // pthread_t p;
    // BlackQueue<Task>* bq=new BlackQueue<Task>();
    // pthread_create(&p,nullptr,product,(void*)bq);
    // pthread_create(&c,nullptr,consume,(void*)bq);

    // pthread_join(c,nullptr);
    // pthread_join(p,nullptr);

    pthread_t c[cSize];
    pthread_t p[pSize];
    BlackQueue<Task>* bq=new BlackQueue<Task>();
    for(size_t i=0;i<cSize;i++)
    {
        pthread_create(c+i,nullptr,consume,(void*)bq);
    }
    for(size_t i=0;i<pSize;i++)
    {
        pthread_create(p+i,nullptr,product,(void*)bq);
    }

    for(size_t i=0;i<cSize;i++)
    {
        pthread_join(c[i],nullptr);
    }
    for(size_t i=0;i<pSize;i++)
    {
        pthread_join(p[i],nullptr);
    }

    delete bq;

    return 0;
}